package mina

import (
	"bgs/util"
	"context"
	"encoding/json"
	"fmt"
)

type subMsgResp struct {
	Errcode int    `json:"errcode"`
	Errmsg  string `json:"errmsg"`
}

type SendNotifyParam struct {
	UserOpenID string // 用户openid
	TemplateID string // 订阅模板id
	Page       string // 点击模板卡片后的跳转页面，仅限本小程序内的页面
	Content    map[string]map[string]interface{}
	MinaState  string // 跳转小程序类型：developer为开发版；trial为体验版；formal为正式版；默认为正式版
}

// SendNotify implements the Handler interface.
func (s *MinaServiceImp) SendNotify(ctx context.Context, ptr *SendNotifyParam) (err error) {
	slog := util.NewContextLogger(ctx, s.slog)

	if ptr.UserOpenID == "" {
		err = fmt.Errorf("请求参数UserOpenID没有设置")
		return
	}
	if ptr.TemplateID == "" {
		err = fmt.Errorf("请求参数TemplateID没有设置")
		return err
	}
	if ptr.Page == "" {
		err = fmt.Errorf("请求参数Page没有设置")
		return err
	}
	if ptr.Content == nil {
		err = fmt.Errorf("请求参数Content没有设置")
		return err
	}
	if ptr.MinaState == "" {
		ptr.MinaState = "formal"
	}

	accessToken, err := s.GetAccessToken(ctx)
	if err != nil {
		return
	}

	apiUrl := s.getURL(fmt.Sprintf("/message/subscribe/send?access_token=%s", accessToken))

	param := map[string]interface{}{
		"touser":            ptr.UserOpenID,
		"template_id":       ptr.TemplateID,
		"page":              ptr.Page,
		"data":              ptr.Content,
		"miniprogram_state": ptr.MinaState,
		"lang":              "zh_CN",
	}

	body, err := util.GetRequest().Send(ctx, "POST", apiUrl, param, nil, 2)
	if err != nil {
		slog.Infof("send subscribe message error => %s", err.Error())
		return err
	}
	resp := &subMsgResp{}
	if errR := json.Unmarshal(body, resp); errR != nil {
		slog.Infof("send subscribe message error => %s", errR.Error())
		return err
	}
	if resp.Errcode != 0 {
		slog.Infof("send subcribe return error => %s ", resp.Errmsg)
		if resp.Errcode != 43101 && resp.Errcode != 47003 && resp.Errcode != 41030 {
			return fmt.Errorf(resp.Errmsg)
		}
	}
	return
}
